//
//  EditingShopTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/12.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "EditingShopTabVC.h"
#import "WriteRequirementTitleCell.h"
#import "TextFieldCell.h"
#import "TextViewCell.h"
#import "UITextView+Placeholder.h"
#import "UpdateLogCell.h"
#import "ButtonCell.h"
#import "ButtonSelectCell.h"
#import "AlterController.h"
#import "ShopModel.h"
#import "TZImagePickerController.h"
#import "CustomePickerImageVC.h"
#import "UIView+TYAlertView.h"
@interface EditingShopTabVC ()<ButtonSelectCellDelegate,AlterControllerProtocol,TextFieldCellDelegate,TextViewCellDelegate,ButtonCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UINavigationBarDelegate,TZImagePickerControllerDelegate,ButtonCellDelegate,UpdateLogCellDelegate>
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager  *manager;
@end

@implementation EditingShopTabVC
static NSString *identifierTitle = @"titleCell";
static NSString *identifierTF = @"tfCell";
static NSString *identifierTextView = @"textViewCell";
static NSString *identifierUpdate = @"updateCell";
static NSString *identifierButton = @"buttonCell";
static NSString *identifierButtonSelect = @"buttonSelectCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"编辑店铺介绍";
    self.manager = [AFHTTPSessionManager manager];
    [self.tableView registerNib:[UINib nibWithNibName:@"WriteRequirementTitleCell" bundle:nil] forCellReuseIdentifier:identifierTitle];
    [self.tableView registerNib:[UINib nibWithNibName:@"TextFieldCell" bundle:nil] forCellReuseIdentifier:identifierTF];
    [self.tableView registerNib:[UINib nibWithNibName:@"TextViewCell" bundle:nil] forCellReuseIdentifier:identifierTextView];
    [self.tableView registerNib:[UINib nibWithNibName:@"UpdateLogCell" bundle:nil] forCellReuseIdentifier:identifierUpdate];
    [self.tableView registerNib:[UINib nibWithNibName:@"ButtonCell" bundle:nil] forCellReuseIdentifier:identifierButton];
    [self.tableView registerClass:[ButtonSelectCell class] forCellReuseIdentifier:identifierButtonSelect];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shopupdate:) name:@"shopupdate" object:nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 3) {
        return 4;
    }else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (indexPath.row == 0) {
        WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        switch (indexPath.section) {
            case 0:
            {
                cell.textLabel.text =  @"店铺名称";
            }
                break;
            case 1:
            {
                cell.textLabel.text =  @"店铺所在城市";
            }
                break;
            case 2:
            {
                cell.textLabel.text =  @"店铺简介";
            }
                break;
            case 3:
            {
                cell.textLabel.text =  @"店铺logo";
            }
                break;
                
            default:
                break;
        }
        return cell;
    }else {
        UITableViewCell *cellNormal = [[UITableViewCell alloc]init];
        cellNormal.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 1) {
            if (indexPath.section == 0 ) {
                TextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTF forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.tf.placeholder = @"请将店铺名称限定在12字内";
                cell.indexPath  = indexPath;
                cell.tf.layer.cornerRadius = 3;
                cell.tf.layer.borderColor  = kOrangeBg.CGColor;
                cell.tf.layer.borderWidth  = 1;
                cell.lineL.hidden = YES;
                cell.delegate = self;
                cell.shopModel = self.model;
                return cell;
            }else if(indexPath.section == 1){
                ButtonSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierButtonSelect forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate = self;
                cell.indexPath = indexPath;
                cell.shopModel = self.model;
//                cell.textLabel.text =  @"店铺名称";
                return cell;
            }else  if (indexPath.section == 2 ) {
                TextViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTextView forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.textView.placeholder = @"请简要介绍本店铺的特点及业务范围优势等";
                cell.indexPath = indexPath;
                cell.shopModel = self.model;
                cell.delegate = self;
                return cell;
            }else {
                UpdateLogCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierUpdate forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.delegate = self;
                cell.shopModel = self.model;
                return cell;
            }

        }else {
            switch (indexPath.row) {
                case 2:
                {
                    ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierButton forIndexPath:indexPath];
                    [cell.btn setTitle:@"保存" forState:UIControlStateNormal];
                    cell.delegate = self;
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    cellNormal = cell;
                }
                    break;
                    
                default:
                    break;
            }
            return cellNormal;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }else if (indexPath.row == 1) {
        if (indexPath.section == 0) {
            return 44;
            
        }else if (indexPath.section == 1) {
            return 44;
            
        }else if (indexPath.section == 2) {
            return 150;
        }else {
            return 100;
        }
    }else {
        return 80;
    }
}
#pragma mark-代理:更改店铺信息
- (void)buttonCell:(ButtonCell *)buttonCell withClickBtn:(UIButton *)clickBtn
{
        if (self.model.title.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入店铺名称"];
        }else if (self.model.city.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请选择店铺所在城市"];
        }else if (self.model.represent.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请填写店铺简介"];
        }else if (self.model.logo.length == 0 ) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请上传店铺logo"];
        }else {
            TYAlertView *alertView = [TYAlertView alertViewWithTitle:@"您确定要更改店铺信息吗?" message:@""];
            
            [alertView addAction:[TYAlertAction actionWithTitle:@"取消" style:TYAlertActionStyleCancel handler:^(TYAlertAction *action) {
                
            }]];
            
            [alertView addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:^(TYAlertAction *action) {
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"title":self.model.title,
                              @"city":self.model.city,
                              @"represent":self.model.represent,
                              @"logo":self.model.logo,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                [CustomeManager POSTWithURLIndex:47 parameters:self.dict success:^(NSDictionary *dict) {
                    
                } failure:^(NSError *error) {
                    
                }];
            }]];
            // first way to show ,use UIView Category
            [alertView showInWindowWithOriginY:200 backgoundTapDismissEnable:YES];
            
        }
}
-(void)shopupdate:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [info.userInfo objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
        if (self.returnValueBlock) {
            self.returnValueBlock(1);
        };
    });
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark-代理:改名字
- (void)textFieldCell:(TextFieldCell *)textFieldCell withTextField:(UITextField *)tf withIndexPath:(NSIndexPath *)indexPath
{
    if (tf.text.length >12) {
//        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请将店铺名称限定在12字内"];
        tf.text = [tf.text substringToIndex:12];
    }
    self.model.title = tf.text;
}
#pragma mark-代理:改店铺介绍
-(void)TextViewCell:(TextViewCell *)TextViewCell withTextView:(nonnull UITextView *)textView withIndexPath:(nonnull NSIndexPath *)indexPath
{
    self.model.represent = textView.text;
}
#pragma mark-代理:点击上传logo
- (void)updateLogCell:(UpdateLogCell *)updateLogCell withLogBtn:(UIButton *)logBtn
{
    //打开照相机和图片
    UIAlertController *sheetControler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    CustomePickerImageVC *picker = [[CustomePickerImageVC alloc]init];
    
    picker.edgesForExtendedLayout =  UIRectEdgeNone;
    picker.automaticallyAdjustsScrollViewInsets = NO;
    
    picker.allowsEditing = YES;
    
    picker.delegate = self;
    sheetControler.popoverPresentationController.sourceView = self.view;
    sheetControler.popoverPresentationController.sourceRect = self.view.frame;
    [self pushTZImagePickerController];
    [self presentViewController:sheetControler animated:YES completion:nil] ;
}
- (void)pushTZImagePickerController {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:3];
    UpdateLogCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    if ([imagePickerVc.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        
        [imagePickerVc.navigationBar setBarTintColor:[UIColor colorWithWhite:0.1 alpha:1.0]];
        
        [imagePickerVc.navigationBar setTranslucent:YES];
        
        [imagePickerVc.navigationBar setTintColor:[UIColor whiteColor]];
        }else{
            [imagePickerVc.navigationBar setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:1.0]];
            
        }
    
    
    imagePickerVc.navigationController.navigationBar.backgroundColor = kOrangeBg;
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];

    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    imagePickerVc.allowTakePicture = YES;
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
  
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;

    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;

#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        XLog(@"photos:%@",photos);

        UIImage *image = photos[0];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        [cell.updateBtn setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        XLog(@"cell.updateBtn :%@",[cell.updateBtn currentImage]);
        //选择回调
        [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            //二进制文件，接口key值，文件路径，图片格式
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                float update = uploadProgress.fractionCompleted*100;
                [WSProgressHUD showWithStatus:[NSString stringWithFormat:@"%.f%%",update]];
                
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *stringImg = [responseObject mj_JSONString];
            NSDictionary *dict = [stringImg mj_JSONObject];
            XLog(@"stringImg:%@",stringImg);
            self.model.logo = [dict objectForKey:@"path"];
            [WSProgressHUD dismiss];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //XLog(@"error:%@",error);
            [WSProgressHUD dismiss];
        }];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    
    // 提前定位
    __weak typeof(self) weakSelf = self;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerVc = [[UIImagePickerController alloc] init];
        imagePickerVc.delegate = self;
        imagePickerVc.sourceType = sourceType;
        
        //        NSMutableArray *mediaTypes = [NSMutableArray array];
        //        if (self.showTakePhotoBtnSwitch.isOn) {
        //            [mediaTypes addObject:(NSString *)kUTTypeImage];
        //        }
        //        if (mediaTypes.count) {
        //            _imagePickerVc.mediaTypes = mediaTypes;
        //        }
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    } else {
        //        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:3];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    
    UpdateLogCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    [cell.updateBtn setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    XLog(@"cell.updateBtn :%@",[cell.updateBtn currentImage]);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    //选择回调
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        //二进制文件，接口key值，文件路径，图片格式
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            float update = uploadProgress.fractionCompleted*100;
            [WSProgressHUD showWithStatus:[NSString stringWithFormat:@"%.f%%",update]];
            
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSString *stringImg = [responseObject mj_JSONString];
        NSDictionary *dict = [stringImg mj_JSONObject];
        XLog(@"stringImg:%@",stringImg);
        self.model.logo = [dict objectForKey:@"path"];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
        [WSProgressHUD dismiss];
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
#pragma mark-代理:选择城市
-(void)buttonSelectCell:(ButtonSelectCell *)buttonSelectCell withBtn:(MCButton *)btn withIndexPath:(NSIndexPath *)indexPath
{
    self.indexPath = indexPath;
    if (btn.selected) {
        
        
    }else{
    }
    AlterController *pickerView = [[AlterController alloc]initWithTitle:@"选择城市" type:kTypeOfCity];
    pickerView.dataArray = [self getCityData];
    pickerView.delegate = self;
    [self presentViewController:pickerView animated:YES completion:nil];
}
#pragma mark - <代理方法实现>
//实现代理方法
-(void)getResultFromPickView:(NSString *)result{
    ButtonSelectCell *cell = [self.tableView cellForRowAtIndexPath:self.indexPath];
//    XLog(@"result:%@",result);
    self.model.city = result;
    cell.mcBtn.selected = NO;
    [cell.mcBtn setTitle:result forState:UIControlStateNormal];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}
#pragma mark - <工具方法>
//获取json中的城市数据
- (NSArray *)getCityData{
    NSString* path = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
    NSString* cityNames = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    if (cityNames == nil) {
        NSLog(@"error:加载城市数据为空");
        return nil;
    }
    NSData *jsonData = [cityNames dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arrayCityNames = [NSJSONSerialization JSONObjectWithData:jsonData
                                                              options:NSJSONReadingMutableContainers
                                                                error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return arrayCityNames;
}
@end
